package com.heima.kafka.sample;

/**
 * @Author yuan
 * @Date 2023/1/30
 * @ApiNote
 */

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 1. kafka链接配置信息
        Properties prop = new Properties();
        // 1.1 kafka链接地址
        prop.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        // 1.2 key 和 value 的序列化
        prop.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        prop.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        // ack配置 消息确认机制
        prop.put(ProducerConfig.ACKS_CONFIG, "all");

        // retries 重试次数
        prop.put(ProducerConfig.RETRIES_CONFIG, 10);

        // 数据压缩
        prop.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");

        // 2. 创建生产者
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(prop);

        // 3. 发送消息
        // ProducerRecord<String, String> kvProducerRecord = new ProducerRecord<String, String>("topic-first", "key-001", "hello kafka");

        // 轮询策略(默认)
        // ProducerRecord<String, String> kvProducerRecord = new ProducerRecord<String, String>("topic-first", "hello kafka");
        // 指定分区号
        ProducerRecord<String, String> kvProducerRecord = new ProducerRecord<String, String>("topic-first", 0,"key-001", "hello kafka");

        //producer.send(kvProducerRecord);

        // 同步发送消息
        /*RecordMetadata recordMetadata = producer.send(kvProducerRecord).get();
        System.out.println(recordMetadata.offset());*/
        // -> 6、7、8...

        // 异步发送消息
        producer.send(kvProducerRecord, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if(e != null) {
                    System.out.println("记录异常信息到日志表中");
                }
                System.out.println(recordMetadata.offset());
            }
        });
        // -> 8、9、10...

        // 4. 关闭消息通道(必须关闭,否则信息发送不成功)
        producer.close();
    }
}
